package com.greenant.store.activity;

import java.util.ArrayList;
import java.util.List;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.greenant.store.AntHomeApplication;
import com.greenant.store.R;
import com.greenant.store.adapter.WeightGoodsListAdapter;
import com.greenant.store.bean.Order;
import com.greenant.store.bean.OrderItem;
import com.greenant.store.bean.OrderStatusCode;
import com.greenant.store.bean.StoreInfo;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.Const;
import com.greenant.store.utils.UtilTools;
import com.greenant.store.utils.iLog;
import com.greenant.store.view.CommonDialog;
import com.lsarah.utils.SystemBarTintManager;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class WeightGoodsActivity extends BaseActivity {
	public static final String KeySendTime = "key_send_time";
	public static final String KeyGoodsList = "key_goods_list";
	private final String TAG = "OrderDetailActivity";

	private View mBackView;

	// private Order order;
	private Context context;
	// 提交按钮
	private TextView modify;
	private ListView orderlist;

	private List<OrderItem> orderItemList = new ArrayList<OrderItem>();
	private List<OrderItem> weightItemList = new ArrayList<OrderItem>();

	WeightGoodsListAdapter weightGoodsListAdapter;

	private final int MSG_TYPE_FEEDBACK = 0;

	private Handler mHandler = new Handler(Looper.getMainLooper());

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v.equals(mBackView)) {
				setResult(RESULT_CANCELED);
				finish();
			}
		}
	};

	private RetrieveDataListener mRetrieveDataListener = new RetrieveDataListener() {
		@Override
		public void dataRetrieved(int requestId, Object data) {

		}
	};

	@Override
	public void onBackPressed() {
		setResult(RESULT_CANCELED);
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SystemBarTintManager.setContentView(this, R.layout.activity_order_weight,
				getResources().getColor(R.color.firebrick));
		context = this;
		mBackView = findViewById(R.id.order_create_top_arrow_left);
		// mBtnCreateOrder = (Button) findViewById(R.id.order_create_btn);
		orderlist = (ListView) findViewById(R.id.orderlist);

		mBackView.setOnClickListener(mOnClickListener);
		// mBtnCreateOrder.setOnClickListener(mOnClickListener);
		weightGoodsListAdapter = new WeightGoodsListAdapter(weightItemList, this);

		orderlist.setAdapter(weightGoodsListAdapter);
		modify = (TextView) findViewById(R.id.modify);
		modify.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isWeighted()) {
					saveOrderDetail();
				} else {
					UtilTools.showMyToast(context, context.getString(R.string.order_msssage_weight));
				}
			}
		});

		initData();
	}

	public boolean isWeighted() {
		if (weightItemList != null && weightItemList.size() > 0) {
			for (int i = 0; i < weightItemList.size(); i++) {
				// 未称重
				if (weightItemList.get(i).isWeighAble()) {
					if (weightItemList.get(i).getWeight() < 0.001) {
						return false;
					}
				}
			}

		}
		return true;
	}



	@Override
	protected void onPause() {
		super.onPause();
		Intent intent = new Intent(Const.ORDER_STATUS_CHANGED);
		sendBroadcast(intent);
	}

	private void saveOrderDetail() {

		if (Const.order != null) {

			Const.order.setStatusCode(OrderStatusCode.ORDER_WEIGHED.value());
			Const.order.saveOrderItems(orderItemList);

			final double totalCost = UtilTools.getTotalCostByOrderItems(orderItemList);

			final StoreInfo storeInfo = AntHomeApplication.storeInfos.get(Const.order.getStoreId());
			if (storeInfo != null) {
				double startCost = storeInfo.getStartcost();

				iLog.d("startCost:" + startCost + "");
				if (startCost > totalCost) {
					Const.order.setDeliveryCost(storeInfo.getDeliverycost());
				} else {
					Const.order.setDeliveryCost(0);
				}
				
			
				iLog.d("startCost:" + startCost + " DeliveryCost:" + Const.order.getDeliveryCost());
			}
			
			if(AntHomeApplication.context.getResources().getString(R.string.order_ensure_send_metho_ziting).equals(Const.order.getDeliveryWay()))
			{
				Const.order.setDeliveryCost(0);
			}

			// 商店支持减免
			if (storeInfo.isHaveDisaccount()) {
				AVQuery<AVUser> users = AVUser.getQuery();
				users.getInBackground(Const.order.getCustomId(), new GetCallback<AVUser>() {
					
					
					@Override
					public void done(AVUser user, AVException arg1) {
						if (user != null) {
							// 是否已经使用过首单减免
							boolean isused = user.getBoolean("firstOrderDiscountUsed");
							if (!isused) {
								// 没使用的话到服务器在实时查询
							
									if (totalCost > storeInfo.getFirstOrderLimit()) {
										Const.order.put(Order.ATTR_FAVORABLECOST,
												storeInfo.getFirstOrderDiscount());
										user.put("firstOrderDiscountUsed", true);
										user.saveInBackground();
									}
								
							}
						}
						realSaveOrder();
					}
				});

				
			}else{
				realSaveOrder();
			}
			
					
			
		}

	}
	
	private void realSaveOrder(){
		
		double totalCostMoney  = UtilTools.getTotalCostByOrderItems(Const.order.getOrderItems());
		
		double realTotalCost=totalCostMoney+Const.order.getDouble(Order.ATTR_DELIVERYCOST)-Const.order.getDouble(Order.ATTR_FAVORABLECOST);
		Const.order.put(Order.ATTR_TOTALCOST, realTotalCost);
		
		Const.order.saveInBackground(new SaveCallback() {

			@Override
			public void done(final AVException arg0) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (arg0 == null) {
							// NotificationUtil.sendPrivateMsg(context.getString(R.string.orderdetail_send_hint,
							// Const.order.getOrderId()),
							// Const.order.getOrderId(), 0,
							// Const.order.getCustomId());
							UtilTools.showMyToast(context, context.getString(R.string.success));
							setResult(RESULT_OK);
							finish();
						} else {
							UtilTools.showMyToast(context, context.getString(R.string.failed));
						}
					}
				});
			}
		});	
	}

	private void refreshOrderDetail() {

		if (Const.order != null) {

			RetrieveDataAsyn.getInstance().getOrderDetail(Const.order.getObjectId(), 0, new RetrieveDataListener() {

				@Override
				public void dataRetrieved(int requestId, Object data) {

					if (data != null) {
						Order tempOrder = (Order) data;

						Const.order.put(Order.ATTR_ORDERITEMS, tempOrder.getString(Order.ATTR_ORDERITEMS));

						Const.order.setStatusCode(tempOrder.getStatusCode());
						Const.order.setAddress(tempOrder.getAddress());
						Const.order.setOrderType(tempOrder.getOrderType());
						Const.order.setPayWay(tempOrder.getPayWay());
						Const.order.setDeliveryTime(tempOrder.getDeliveryTime());
						Const.order.setDeliveryWay(tempOrder.getDeliveryWay());
						Const.order.setPayTime(tempOrder.getPayTime());
						Const.order.setTotalCost(tempOrder.getTotalCost());
						Const.order.setDeliveryCost(tempOrder.getDeliveryCost());
						initData();

					}
				}
			});

		} else {
		}

	}

	private void initData() {
		if (Const.order == null) {
			return;
		}

		orderItemList.clear();
		List<OrderItem> items = Const.order.getOrderItems();
		iLog.d(TAG, "tempList1 getOrderItems size:" + items.size() + " orderItemList:" + orderItemList.size());
		orderItemList.addAll(items);

		weightItemList.clear();

		for (int i = 0; i < items.size(); i++) {
			iLog.d(TAG, "tempList1 getOrderItems items:" + items.get(i).getWeight() + " items size:" + items.size()
					+ " orderItemList:" + orderItemList.size());
			if (items.get(i).isWeighAble()) {
				weightItemList.add(items.get(i));
			}
		}

		weightGoodsListAdapter.notifyDataSetChanged();

	}

	public void makeaCall(View view) {

		final String tele = Const.order.getPhone();
		if (!TextUtils.isEmpty(tele)) {
			CommonDialog errDialog = new CommonDialog(context,
					context.getString(R.string.common_title), context.getString(R.string.orderdetail_call));
			errDialog.setSureListener(new CommonDialog.OnSureClickListener() {

				@Override
				public void sureClicked() {
					Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tele));
					startActivity(intent);
				}
			});
			errDialog.show();

		}

	}

}
